package com.axapoint.opoc.core.dao;

import java.util.ArrayList;

import org.joda.time.DateTime;
import org.joda.time.Interval;

import com.axapoint.opoc.core.UserException;

public class LocationFacade extends AbstractFacade<Location, Location.Value, Location.Bitemporal> {

	public LocationFacade(String systemId, String userId) {
		super(systemId, userId, new Location(), new Location.Value());
	}
	
	public UnitLocation.Value[] getUnitLocations(String uuid, DateTime at) {
		Location pd = getEntity(uuid);
		if (pd == null) throw new UserException("Ingen adresse med UUID: " + uuid);
		
		ArrayList<UnitLocation.Value> result = new ArrayList<UnitLocation.Value>();
        for (UnitLocation.Value v : pd.getUnitLocations()) {
        	if (at == null || v.getBitemporal().getValidityInterval().contains(at)) {
        		result.add(v);
        	}
        }
		
		return result.toArray(new UnitLocation.Value[0]);
	}

	public Unit.Value[] getUnits(String uuid, DateTime at) {
		Location e = getEntity(uuid);
		if (e == null) throw new UserException("Ingen adresse med UUID: " + uuid);
		
		ArrayList<Unit.Value> result = new ArrayList<Unit.Value>();
        for (UnitLocation.Value v : e.getUnitLocations()) {
        	if (at == null || v.getBitemporal().getValidityInterval().contains(at)) {
        		result.add(v.getUnit().getValues().get(at).getValue());
        	}
        }
		
		return result.toArray(new Unit.Value[0]);
	}

	@Override
	public ObjectRegistration[] getAffectedEntities(String uuid, Interval newInterval) {
		ArrayList<ObjectRegistration> result = new ArrayList<ObjectRegistration>();
		
		Location location = getEntity(uuid);
		
		// Check unitlocations
		for (UnitLocation.Value l : location.getUnitLocations()) {
			Interval i = l.getEntity().getValues().get(newInterval.getStart()).getValidityInterval();
			
			// If the unit location does not have interval this can contain new location it is affected
			if (!i.contains(newInterval)) {
				result.add(l.getEntity());
			}
		}
		
		return result.toArray(new ObjectRegistration[0]);
	}
}